<?php
class Apps_Controller_Action extends Zend_Controller_Action {
	const MSG_CLASS_ERROR   = 'alert-error';
	const MSG_CLASS_SUCCESS = 'alert-success';
	const MSG_CLASS_INFO 	= 'alert-info';
	const MSG_CLASS_WARNING = 'alert-warning';
	const MSG_CLASS_NOCLASS = '';

	public static $msgUpdateSuccess = array(self::MSG_CLASS_SUCCESS => 'Cập nhật dữ liệu thành công!');
	public static $msgUpdateFailed  = array(self::MSG_CLASS_ERROR   => 'Cập nhật dữ liệu không thành công.');
	public static $msgAddSuccess    = array(self::MSG_CLASS_SUCCESS => 'Cập nhật dữ liệu  thành công!');
	public static $msgAddFailed     = array(self::MSG_CLASS_ERROR   => 'Cập nhật dữ liệu không thành công.');
	public static $msgDeleteSuccess = array(self::MSG_CLASS_SUCCESS => 'Cập nhật dữ liệu thành công!');
	public static $msgDeleteError   = array(self::MSG_CLASS_ERROR   => 'Cập nhật dữ liệu không thành công.');
	public static $msgUnknownError  = array(self::MSG_CLASS_ERROR   => 'Có lỗi xảy ra, xin vui lòng thử lại.');
	public static $msgNoRecordFound = array(self::MSG_CLASS_ERROR   => 'Không tìm thấy dữ liệu.');
	public static $msgMalformData   = array(self::MSG_CLASS_ERROR   => 'Dữ liệu không hợp lệ.');

	protected $_namespaceRequestedParams = 'App.Paper';

    protected $_allowBacktrack = false;
    protected $_flashMessenger;
	protected $_dbAdapter;
	protected $_auth;

	protected $_page_title         = 'Ohnew.com.vn';
	protected $_page_meta_keywords = '';
	protected $_page_meta_description = '';


	/* DISPATCH OVERWRITTEN */
		final public function init() {
		     $this->_auth = Zend_Auth::getInstance();
             if (!$this->_auth->hasIdentity()
                     && $this->_request->getModuleName() != 'a'
                     && $this->_request->getControllerName() != 'in'
                     && $this->_request->getActionName() != 'index')
             {
                $this->saveRequestedParams();
            	//$this->_redirect('/a/in');
             }

            // Get default db adapter
			$this->_dbAdapter = Zend_Db_Table::getDefaultAdapter();

			$rq = $this->_request;

			// Init flash messenger
	        $this->_flashMessenger = new Zend_Controller_Action_Helper_FlashMessenger();

			$this->_allowBacktrack = !$rq->isXmlHttpRequest();

	        $this->_init(); // Call to-be-extented method
		}
		public function preDispatch() {
			$this->view->app_backtrackUrl = $this->getBacktrackUrl();

			$rq = $this->_request;
			$this->view->app_action     = $rq->getActionName();
			$this->view->app_controller = $rq->getControllerName();
			$this->view->app_module     = $rq->getModuleName();

			$this->_preDispatch(); // Call to-be-extented method
		}
        final public function postDispatch() {
            // Save Backtrack URL - used in Requested
            if($this->_allowBacktrack) { $this->saveRequestedParams();}

            // Set page
            $view = $this->view;

            // Set meta
            $controller = $this->_request->getControllerName();
            $action = $this->_request->getActionName();
            if(($controller != 'product' && $action != 'detail' )
                    || ($controller != 'product' && $action != 'category'))
            {
                $tbSetting = new Model_DbTable_SiteSetting();
                $setting   = $tbSetting->getMetaTag();

                $this->_page_title    = ($this->_request->getModuleName() == 'default')
                                        ? ($setting['header_title'] ? $setting['header_title'] : $this->_page_title)
                                        : "";

                $this->_page_meta_keywords    = ($this->_request->getModuleName() == 'default')
                                                ? ($setting['meta_keyword'] ? $setting['meta_keyword'] : $this->_default_keyword )
                                                : "";
                $this->_page_meta_description = ($this->_request->getModuleName() == 'default')
                                                ? ($setting['meta_description'] ? $setting['meta_description'] : $this->_default_description)
                                                : "";
            }

            $view->headTitle($this->_page_title);
            $view->headMeta()->setName('keywords'   , $this->_page_meta_keywords);
            $view->headMeta()->setName('description', $this->_page_meta_description);

            // Call to-be-extented method
            $this->__postDispatch();
            $this->_postDispatch();
        }

		/* To be extended by subclass (instead of original public methods) */
		protected function _init() {}
	    protected function _preDispatch(){}
		protected function _postDispatch(){}

	/* BACK TRACKING
	 *  Used to save request params
	 *     for tracing back (especially in back-button)
	 */
	    public function saveRequestedParams($v='requestedUrlParams', $namespace=null) {
	    	if(!$namespace) { $namespace = $this->_namespaceRequestedParams; }

	        $customerSession = new Zend_Session_Namespace($namespace);
	        $customerSession->$v = $this->_request->getParams();

	        return $this;
	    }
	    public function loadRequestedParams($v='requestedUrlParams', $namespace=null) {
	        if(!$namespace) { $namespace = $this->_namespaceRequestedParams; }

	    	$customerSession = new Zend_Session_Namespace($namespace);
	        return isset($customerSession->$v)
	               ? $customerSession->$v
	               : array();
	    }

	    /** Shortcut for getting Requested params url */
	    public function getBacktrackUrl($namespace=null) {
	        $params = $this->loadRequestedParams('requestedUrlParams', $namespace);

	        // Prevent loop forever
	        if($params == $this->_request->getParams()) {
	            $params = array();
	        }

	        return $this->view->url($params);
	    }
	    public function disallowBacktrack() {
	    	$this->_allowBacktrack = false;
	    	return $this;
	    }
	    public function allowBacktrack() {
	    	$this->_allowBacktrack = true;
	    	return $this;
	    }

	    public function goBack() {
	        return $this->_redirect($this->getBacktrackUrl());
	    }
	    public function goToActionIndex() {
	        return $this->_helper->redirector('index');
	    }
	    public function goToControllerIndex() {
	        return $this->_helper->redirector('index', 'index');
	    }

    /* HELPER */
    public function refresh($params=array()) {
    	$rq = $this->_request;

    	return $this->_helper->redirector(
    	           $rq->getActionName(),
    	           $rq->getControllerName(),
    	           $rq->getModuleName(),
    	           $params);
    }
    public function disableLayout($disableLayout=null, $disableView=null) {
    	if($disableLayout === true) {
    		$this->_helper->layout()->disableLayout();
    	} else if($disableLayout === false) {
    		$this->_helper->layout()->enableLayout();
    	}
    	if($disableView === true) {
    		$this->_helper->viewRenderer->setNoRender(true);
    	} else if($disableView === false) {
    		$this->_helper->viewRenderer->setNoRender(false);
    	}
    }
    public function ajaxOnly($disableLayout=true, $disableView=true) {
        if(!$this->_request->isXmlHttpRequest()) {
            $this->_redirect('/');
        }
        $this->disableLayout($disableLayout, $disableView);
    }
    public function ajaxRefresh($url=null, $msg=null) {
        if(null == $url) {
            $url = $this->getBacktrackUrl();
        }
        if(null == $msg) {
            $msg = 'Update successfully, please wait ...';
        }
        // Send Refresh JS
        echo '<script>window.location.reload()</script><a style="padding:10px 0;display:block;width:100%;text-align:center" href="'
             ,$url, '">', $msg, '</a>';
    }

    public function actResolve($act, $resolveAction=null, $resolveController=null, $resolveModule=null, $resolveParams=null,$redirect=true) {
        $rq = $this->_request;

        if($rq->isPost() && $rq->getParam($act)) {
            // Parameters
                if(null === $resolveParams) {
                    $resolveParams = $rq->getParams();
                }

            if($redirect) {
                $this->_helper->redirector($resolveAction, $resolveController, $resolveModule, $resolveParams);
            } else {
                $this->_forward($resolveAction, $resolveController, $resolveModule, $resolveParams);
            }
        }
        return $this;
    }

    public function deserializeParam($field, $delimiter=null) {
        return Apps_View_Helper_SerializeParam::deserializeParam($field, $delimiter);
    }

    /* NO ACTION FOUND */
    public function __call($method, $args) {
    	if('Action' == substr($method, -6)) {
 //   		$this->_redirect('/');
    	}
    }
}